package com.qkst.website.web.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qkst.website.web.bean.CommentBean;
import com.qkst.website.web.mapper.CommentMapper;
import com.qkst.website.web.mapper.CommentRelAccessoryMapper;
import com.qkst.website.web.service.CommentService;

/**
 * @author lihao
 * @description 评论 service
 * @date 2017-05-12
 * @email ahlxlihao@163.com
 *
 */
@Service("commentService")
@Transactional
public class CommentServiceImpl implements CommentService {
	
	@Autowired
	private CommentMapper commentMapper;
	
	@Autowired
	private CommentRelAccessoryMapper commentRelAccessoryMapper;
	
	/**
	 * 根据条件查询评论
	 * @param comment
	 * @return List<CommentBean>
	 */
	public List<CommentBean> queryCommentList(CommentBean comment){
		//分页计算
		return commentMapper.selectCommentList(comment);
	}
	
	/**
	 * 查询评论总记录数
	 * @param comment
	 * @return 
	 */
	@Override
	public int queryCount(CommentBean comment) {
		return commentMapper.selectCount(comment);
	}

	
	/**
	 * 添加评论
	 * @param comment
	 * 
	 */
	@Override
	public void save(CommentBean comment,Map<String, Object> result) {
		comment.setCreateTime(new Date());
		comment.setLastUpdate(new Date());
		int num=commentMapper.insert(comment);//插入
		result.put("comment",comment);
		if(num>0){//插入成功
			if(comment.getCommentRelAccessoryList()!=null && !comment.getCommentRelAccessoryList().isEmpty()){//插入附件信息
				num=commentRelAccessoryMapper.batchInsert(comment);
			}
			if(num>0){
				result.put("isSuccess", true);
				result.put("code", "000");
			}else{
				result.put("isSuccess", false);
				result.put("code", "002");
			}
		}else{//插入失败
			result.put("isSuccess", false);
			result.put("code", "500");
		}
	}
	
	/**
	 * 删除评论
	 * @param comment
	 * @return 
	 */
	@Override
	public void delete(CommentBean comment, Map<String, Object> result) {
		if(comment.getCommentId()!=null){
			int num=commentMapper.deleteByPrimaryKey(comment.getCommentId());
			if(num>0){//删除成功
				List<CommentBean> commentList=commentMapper.selectCommentChildrenByKey(comment);//获取当前评论的子评论
				if(commentList!=null && !commentList.isEmpty()){
					for(CommentBean cmt  : commentList){
						delete(cmt,result);
					}
				}
				result.put("comment",comment);
				commentRelAccessoryMapper.deleteByComment(comment);//删除评论和附件的关系
				result.put("isSuccess", true);
				result.put("code", "000");
			}else{//删除失败
				result.put("isSuccess", false);
				result.put("code", "500");
			}
		}else{
			result.put("isSuccess", false);
			result.put("code", "404");
		}
		
	}
	
}
